package com.shop2cn.iapi.sqoptrade.testcase;

import java.math.BigDecimal;

import com.ymttest.business.service.shenqi.SqTradingBookingOrderCallService;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.shop2cn.iapi.shenqisettlement.parameter.OnHpSettledReq;
import com.shop2cn.iapi.shenqisettlement.parameter.bean.AgentProductBean;
import com.shop2cn.iapi.shenqisettlement.service.OnHpSettledCall;
import com.shop2cn.iapi.sqoptrade.parameter.req.AcceptOrderReq;
import com.shop2cn.iapi.sqoptrade.parameter.utill.Utils;
import com.shop2cn.iapi.sqoptrade.resp.TradingServiceResp;
import com.shop2cn.iapi.sqoptrade.service.SellerAcceptOrderCall;
import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P3;
import com.ymttest.business.service.SQPayGateWayCallService;
import com.ymttest.business.service.shenqi.DGSQBuildProxyChainCallService;
import com.ymttest.business.service.shenqi.SqTradingCallService;
import com.ymttest.business.service.shenqi.bean.ShenqiUserSet;
import com.ymttest.database.sharding.db.ext.model.PickUpCodePo;
import com.ymttest.database.sharding.db.sharding.model.OrderPo;
import com.ymttest.database.sharding.db.sharding.model.OrderStatusLogPo;
import com.ymttest.database.sharding.db.sharding.model.PaymentPo;
import com.ymttest.database.sharding.db.sharding.model.PickInStorePo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.database.sharding.db.sqlwapper.OrderWapper;
import com.ymttest.utils.constant.ECode;

public class Ts_SqSellerAcceptOrder {
	
	private static AcceptOrderReq acceptorderbean;
	private static SellerAcceptOrderCall acceptordercall;
	
	private static OnHpSettledReq hpSettledReq = new OnHpSettledReq();
	private static OnHpSettledCall hpSettledCall = new OnHpSettledCall();

	private static OrderShardingWapper database = new OrderShardingWapper();
	private static long autotest_goodsOwnerId = ShenqiUserSet.autotest_goodsOwnerId;
	private static long japanGoodsOwnerId = ShenqiUserSet.japanGoodsOwnerId;
	private static long multiCDFCodeGoodsOwnerId = ShenqiUserSet.multiCDFCodeGoodsOwnerId;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("卖家接单");
	}

	@Before
	public void caseUp() {
		acceptorderbean = new AcceptOrderReq();
		acceptordercall = new SellerAcceptOrderCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(acceptordercall.getOpurl());
		database.activeDeadCommunicationsLink(database);
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	/**
	 * 校验订单表状态，单主状态操作日志表
	 */
	public static void verifyOrderStatus(long orderId, long sellerId,
			boolean isAuto, Integer pickupType) {

		// 订单表(order)
		OrderPo ymtOrders = database.selectOrderbyOrderId(orderId);

		Logger.comment(String.format("验证订单表(order)表 orderId: %s", orderId));

		Logger.verifyEquals(17, ymtOrders.getOrderStatus(), "验证orderStatus");

		// 订单主状态操作日志表(order_status_log)
		OrderStatusLogPo orderStatusLogPo = database
				.selectOrderStatusLogByOrderId(orderId);

		Logger.comment("验证订单主状态操作日志表(order_status_log)");

		String memo = "接单";

		if (isAuto) {
			memo = "系统自动接单";
		}
		
		if (ymtOrders.getSalesman() > 0 && acceptorderbean.getCsId() != 0)
			memo = String.format("客服【 %s】接单", acceptorderbean.getCsId());

		Logger.verifyEquals(memo, orderStatusLogPo.getMemo(), "验证数据库Memo");

		Logger.verifyEquals(17, orderStatusLogPo.getOrderStatus(),
				"验证数据库OrderStatus");

		Logger.verifyEquals(true,
				Utils.calcTimeSpanMin(orderStatusLogPo.getAddTime()) < 2,
				"验证数据库AddTime跟系统当前时间差为2分钟内");

		Logger.verifyEquals(orderId, orderStatusLogPo.getOrderId(),
				"验证数据库OrderId");
		Logger.verifyEquals(sellerId, orderStatusLogPo.getOperator(),
				"验证数据库Operator");
		
		if (null != pickupType) {
			
			verifyPickupInfo(orderId, pickupType, ymtOrders.getGoodsOwnerId());
		}
	}
	
	public static void verifyPickupInfo(long orderId, Integer pickupType,
			Long goodsOwnerId) {

		Logger.comment("验证自提信息");

		PickInStorePo pickInStorePo = database.selectPickInStorebyOrderId(
				orderId).get(0);

		Logger.verifyEquals(pickupType == 0 ? (byte) 2 : (byte) 0,
				pickInStorePo.getPickupStatus(), "验证PickupStatus");

		OrderWapper orderWapper = new OrderWapper();

		PickUpCodePo pickUpCodePo = orderWapper
				.selectPickUpCodeByOrderId(orderId);

		Logger.verifyNotNull(pickUpCodePo.getPickupCode(), "验证PickupCode不为空");
		Logger.verifyEquals(goodsOwnerId, pickUpCodePo.getGoodsOwnerId(),
				"验证GoodsOwnerId");

		Logger.verifyEquals(pickInStorePo.getPickupCode(),
				pickUpCodePo.getPickupCode(), "验证PickupCode");
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_SellerAcceptOrder_002() {
		Logger.start(false, "订单不存在，卖家接单失败");
		try {
			Integer OrderId = 1048827;
			int SellerId = 288484;
			// 接单
			acceptorderbean.setOrderId(OrderId);// 订单ID
			Logger.comment("SellerId:" + SellerId);
			acceptorderbean.setSellerId(SellerId);// 卖家ID
			// 发送请求
			acceptordercall.setData(acceptorderbean);
			acceptordercall.callService();
			Logger.verifyEquals(Integer.valueOf(ECode.FAILED201),
					acceptordercall.getCode(), "验证Code");
			Logger.verifyEquals("订单号" + OrderId + "不存在",
					acceptordercall.getMsg(), "验证Msg");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_SellerAcceptOrder_006() {
		Logger.start(false, "卖家用户id为null");
		try {
			// 接单
			acceptorderbean.setOrderId(1111);// 订单ID
			// acceptorderbean.setSellerId(sellerId+1);// 卖家ID
			// 发送请求
			acceptordercall.setData(acceptorderbean);
			acceptordercall.callService();
			Logger.verifyEquals(201, acceptordercall.getCode(),
					"验证Code");
			Logger.verifyEquals("订单号" + acceptorderbean.getOrderId() + "不存在",
					acceptordercall.getMsg(), "验证Msg");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_SellerAcceptOrder_026() {
		Logger.start(true, "神器订单,商家接单成功，传入csId");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createJPProxychain((int) japanGoodsOwnerId, 1, false);
			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder(productBean, japanGoodsOwnerId);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(3000);

			long paymentId = database.selectOrderbyOrderId(orderId)
					.getPaymentId();

			PaymentPo payment = database.selectPaymentById(paymentId);

			// hp结算
			hpSettledReq.setTradingId(paymentId);
			hpSettledReq.setOrderAmount(payment.getRealPaidAmount());
			hpSettledReq.setSettleCurrency(payment.getSettleCurrency());
			hpSettledReq
					.setSettleAmount(payment.getRealForeignAmount() != null ? payment
							.getRealForeignAmount() : payment
							.getForeignAmount());

			hpSettledCall.setData(hpSettledReq);
			hpSettledCall.callService();
			Logger.comment("前置数据准备结束");
			
			// 接单
			acceptorderbean.setOrderId(orderId);// 订单ID
			acceptorderbean.setSellerId(japanGoodsOwnerId);// 卖家ID
			acceptorderbean.setCsId(1234);

			// 发送请求
			acceptordercall.setData(acceptorderbean);
			acceptordercall.callService();
			Logger.verifyEquals(200, acceptordercall.getCode(),
					"验证Code");
			// 数据库验证
			verifyOrderStatus(orderId, japanGoodsOwnerId, false, null);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_SellerAcceptOrder_027() {
		Logger.start(true, "神器订单,商家接单成功，传入csId为0");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 1, false);
			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder(productBean);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(3000);

			long paymentId = database.selectOrderbyOrderId(orderId)
					.getPaymentId();

			PaymentPo payment = database.selectPaymentById(paymentId);

			// hp结算
			hpSettledReq.setTradingId(paymentId);
			hpSettledReq.setOrderAmount(payment.getRealPaidAmount());
			hpSettledReq.setSettleCurrency(payment.getSettleCurrency());
			hpSettledReq
					.setSettleAmount(payment.getRealForeignAmount() != null ? payment
							.getRealForeignAmount() : payment
							.getForeignAmount());

			hpSettledCall.setData(hpSettledReq);
			hpSettledCall.callService();
			Logger.comment("前置数据准备结束");
			
			// 接单
			acceptorderbean.setOrderId(orderId);// 订单ID
			acceptorderbean.setSellerId(autotest_goodsOwnerId);// 卖家ID
			acceptorderbean.setCsId(1234);

			// 发送请求
			acceptordercall.setData(acceptorderbean);
			acceptordercall.callService();
			Logger.verifyEquals(200, acceptordercall.getCode(),
					"验证Code");
			// 数据库验证
			verifyOrderStatus(orderId, autotest_goodsOwnerId, false, null);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
//	@Ignore
	// 在开发库，shenqirisk.customs_year_statistic表中插入数据
	public void Tc_SellerAcceptOrder_028() {
		Logger.start(true, "代购神器交易下单,自动接单，自动接单时，被风控拦截");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false);
				
//			AgentProductBean productBean = DGSQBuildProxyChainCallService
//					.createMultiCodeProxychain(500041475, false);
			
			TradingServiceResp placeOrder = SqTradingCallService
					.placeOrderWithPurchaserIdcardId(productBean,
							3L);

			long userId = placeOrder.getUserId();
//			long orderId = placeOrder.getOrderList().get(0).getOrderId();// 支付订单
			
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrder.getTradingId());
			
			BigDecimal totalPrice = placeOrder.getPayableAmount();

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					(int) userId, BigDecimal.ZERO.toPlainString());

			Logger.comment("前置数据准备结束");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	@Ignore
	// 在orderdb_ext.shenqi_auto_accept_config配置wait_minutes
	public void Tc_SellerAcceptOrder_029() {
		Logger.start(true, "代购神器交易下单,延迟自动接单");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false);

			TradingServiceResp placeOrder = SqTradingCallService
					.placeOrder(productBean);

			long userId = placeOrder.getUserId();
			long orderId = placeOrder.getOrderList().get(0).getOrderId();// 支付订单
			
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrder.getTradingId());
			
			BigDecimal totalPrice = placeOrder.getPayableAmount();

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					(int) userId, BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(3000);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	@Ignore
	// 在开发库，手机号满足place_order_blacklist表中数据
	public void Tc_SellerAcceptOrder_030() {
		Logger.start(true, "代购神器交易下单,自动接单，自动接单时，被风控拦截");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createMultiCodeProxychain((int) 500041475, false);

			TradingServiceResp placeOrder = SqTradingCallService
					.placeOrderWithBlackList(productBean, 3L, 500041475L);

			long userId = placeOrder.getUserId();
			
//			Long thirdTradingId = TradingForDGSQCallService.payOrder(userId,
//					placeOrder.getTradingId());
			
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrder.getTradingId(), true);
			
			BigDecimal totalPrice = placeOrder.getPayableAmount();

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					(int) userId, BigDecimal.ZERO.toPlainString());
			
			Logger.comment("前置数据准备结束");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_SellerAcceptOrder_031() {
		Logger.start(true, "神器订单,买家预约自提，商家接单成功");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false);
			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrderWithSelfPickup(productBean, autotest_goodsOwnerId, true);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(3000);
			
			Logger.comment("前置数据准备结束");
			
			// 接单
			acceptorderbean.setOrderId(orderId);// 订单ID
			acceptorderbean.setSellerId(autotest_goodsOwnerId);// 卖家ID
			acceptorderbean.setCsId(1234);

			// 发送请求
			acceptordercall.setData(acceptorderbean);
			acceptordercall.callService();
			Logger.verifyEquals(200, acceptordercall.getCode(),
					"验证Code");
			// 数据库验证
			verifyOrderStatus(orderId, autotest_goodsOwnerId, false, 0);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_SellerAcceptOrder_032() {
		Logger.start(true, "神器订单,商家通知自提订单，商家接单成功");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false);
			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrderWithPickupType(productBean, autotest_goodsOwnerId, 1);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(3000);
			
			Logger.comment("前置数据准备结束");
			
			// 接单
			acceptorderbean.setOrderId(orderId);// 订单ID
			acceptorderbean.setSellerId(autotest_goodsOwnerId);// 卖家ID
			acceptorderbean.setCsId(1234);

			// 发送请求
			acceptordercall.setData(acceptorderbean);
			acceptordercall.callService();
			Logger.verifyEquals(200, acceptordercall.getCode(),
					"验证Code");
			// 数据库验证
			verifyOrderStatus(orderId, autotest_goodsOwnerId, false, 1);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_SellerAcceptOrder_033() {
		Logger.start(false, "预售库存未核销订单，卖家接单失败");
		try {

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createMultiCodeProxychainForPreSale(
							(int) multiCDFCodeGoodsOwnerId, false);

			TradingServiceResp resp = SqTradingBookingOrderCallService.placePreSaleActivitySecondConfirmOrder(
					productBean);

			Long userId = resp.getUserId();
			Long orderId = resp.getOrderList().get(0).getOrderId();

			// 支付尾款
			long thirdTradingId = SqTradingBookingOrderCallService.payBookingOrder(userId,
					resp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					resp.getPayableAmount().subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString(),
					productBean.getCurrency());

			Thread.sleep(5000);

			// 接单
			acceptorderbean.setOrderId(orderId);// 订单ID
			acceptorderbean.setSellerId(multiCDFCodeGoodsOwnerId);// 卖家ID

			// 发送请求
			acceptordercall.setData(acceptorderbean);
			acceptordercall.callService();

			Logger.verifyEquals(Integer.valueOf(ECode.FAILED201),
					acceptordercall.getCode(), "验证Code");
			Logger.verifyEquals(String.format("当前订单[%s]未核销不能确认接单", orderId),
					acceptordercall.getMsg(), "验证Msg");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}
